﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Windows.Markup;
using System.Xml;
using System.Xml.Serialization;


namespace editor
{
    public enum MainState {

        Move,
        Remove,
        LifeLine,
        AMessage,
        SelfMessage,
        Comment
    };

    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window {

        public static MainWindow kMainWindow;

        int tekuhee_load = -1, count_save = 0;   //текущие загружаемый файл номерр сохранения

        String save_undo_rendo = "./save_undo_redo/strn";

        // Undo/Redo
        UndoRedoManager undoManager = new UndoRedoManager();

        int nextIdentifier = 0;

        // MainState
        public MainState state = MainState.Move;

        System.Drawing.Size s;

        public UIViewProtocol initialObject;
        public UIViewProtocol currentObject;
        public Point initialPosition;
        public Point currentPosition;
        bool copyCompleted = true;

        public List <LifeLine> lifeLinesList;
        public List <CommentBox> commentsList;
        public List<Arrow> arrowsList;


        public MainWindow()
        {
            InitializeComponent();

            kMainWindow = this;

            arrowsList = new List<Arrow>();
            commentsList = new List<CommentBox>();
            lifeLinesList = new List<LifeLine>();
        }

        public static MainWindow shared()
        {
            if (kMainWindow == null) {

                kMainWindow = new MainWindow();
            }
            return kMainWindow;
        }

        public int getId()
        {
            return nextIdentifier++;
        }

        //рисование линии
        Line lineshapes;

        //линия связи
        Arrow arrow;
        
        
        //линия жизни
        LifeLine lifeLine;

        //отображает комент
        CommentBox commentBox; 
   

        private bool redacto;

        //рисование линий
        private  int numb=1;


        //удаление
        private bool Remove;

        //перетаскивание линии жизни
        private bool life_time_capture;

        //перетаскивание фигуры
        private bool fiure;


        private bool linr_;
        private double x2;
        private double x1, zoom=1;


        private bool point_x1;


        //рисование стрелки
        private bool str_asinh;
        private double X_F;

        //начальная позиция для рисование стрелки и линии времени 
        private double X_0;   
     
        //координата y для второой линии жизни
        private double rect_2_Y;   
        private double line_Y2;
        //событие с возвратом
        private bool event_return;


        private void crete_Click(object sender, RoutedEventArgs e)
        {
            Rectangle rect1 = new Rectangle();
            rect1.Height = rect1.Width = 32;
            rect1.Fill = Brushes.Blue;
            Canvas.SetTop(rect1, 30);
            Canvas.SetLeft(rect1, 30);
            mainCanvas.Children.Add(rect1);
        }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//----------------------------------------------перетаскивание элементов-------------------------------------------------------//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


        private void MainWindow_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.LeftShift)
            {
                if (currentObject != null && copyCompleted == true)
                {
                    copyCompleted = false;

                    // create new obj
                    currentObject = initialObject.copy();

                    // move old obj to start pos
                    initialObject.move(initialPosition);
                }
            }

        }

        private void MainWindow_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.LeftShift)
            {
                if (currentObject != null && copyCompleted == false)
                {
                    // move old obj to new pos
                    UIElement view = (UIElement)currentObject;
                    initialObject.move(new Point(Canvas.GetLeft(view), Canvas.GetTop(view)));
                    
                    // rm new obj
                    currentObject.rmObject();
                    currentObject = initialObject;

                    copyCompleted = true;
                }
            }
        }


        public void objectCaptured(UIViewProtocol anObject, Point relativePosition)
        {
            if (state == MainState.Remove)
            {
                anObject.rmObject();
            }
            else
            {
                initialObject = anObject;
                currentObject = anObject;

                UIElement view = (UIElement)anObject;
                initialPosition = new Point(Canvas.GetLeft(view), Canvas.GetTop(view));
                currentPosition = relativePosition;

                if ((System.Windows.Forms.Control.ModifierKeys & Keys.Shift) != 0)
                {
                    copyCompleted = false;

                    // create new obj
                    currentObject = initialObject.copy();
                }
            }
        }
        public void releaseObject()
        {
            currentObject = null;
            initialObject = null;

            copyCompleted = true;
        }

        private void MouseDidMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (currentObject != null)
            {
                Point point = e.GetPosition(mainCanvas);
                point.Offset(initialPosition.X - currentPosition.X, initialPosition.Y - currentPosition.Y);

                currentObject.move(point);
            }
        }

        private void MouseButtonUp(object sender, MouseButtonEventArgs e)
        {

            xn = e.GetPosition(mainCanvas).X;

            if (fiure == true)
            {
                //был выбран элемент

                UIElement figura = (UIElement)Mouse.Captured;
                if (figura != null)
                {
                    //задаем позицию захваченному элементу
                    Canvas.SetTop(((UIElement)figura), e.GetPosition(mainCanvas).Y);
                    Canvas.SetLeft(((UIElement)figura), e.GetPosition(mainCanvas).X);
                    Mouse.Capture(null);
                    fiure = false;
                }
            }

            if (linr_ == true)
            {
                //была захвачена линия
                linr_ = false;
                UIElement figura = (UIElement)Mouse.Captured;
                if (figura != null)
                {
                    if (point_x1 == true)
                    {//была выбрана начальная точка линии
                        ((Line)figura).X1 = e.GetPosition(mainCanvas).X;
                        ((Line)figura).Y1 = e.GetPosition(mainCanvas).Y;
                        point_x1 = false;
                    }
                    else
                    {
                        //была выбрана конечная точка линии
                        ((Line)figura).X2 = e.GetPosition(mainCanvas).X;
                        ((Line)figura).Y2 = e.GetPosition(mainCanvas).Y;
                    }
                    Mouse.Capture(null);
                }
            }

            this.releaseObject();
        }

        private void MouseButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (redacto == true)
            {
                Remove = false;
                lineshapes.X2 = e.GetPosition(mainCanvas).X;
                lineshapes.Y2 = e.GetPosition(mainCanvas).Y;
                redacto = false;
            }
            if (lineButton.IsChecked == true)
            {
                Remove = false;
                if (numb == 1)
                {
                    numb--;

                    lineshapes = new Line();
                    lineshapes.X1 = e.GetPosition(mainCanvas).X;
                    lineshapes.Y1 = e.GetPosition(mainCanvas).Y;

                    lineshapes.StrokeEndLineCap = PenLineCap.Triangle;  //задает наконечник
                    lineshapes.Stroke = Brushes.Black;                   //способ закраски контура fill не исполь solicolorbrash

                    lineshapes.StrokeMiterLimit = 10;
                    DoubleCollection D_C_l = new DoubleCollection(2);
                    D_C_l.Add(4);
                    D_C_l.Add(2);
                    lineshapes.StrokeDashArray = D_C_l;                  //задает пунктир
                    lineshapes.StrokeThickness = 2;                    //задает толщину
                }
                else
                {
                    numb = 1;

                    lineshapes.X2 = e.GetPosition(mainCanvas).X;
                    lineshapes.Y2 = e.GetPosition(mainCanvas).Y;
                    //layer = AdornerLayer.GetAdornerLayer(lineshapes);
                    //adorner = new strelka_(lineshapes);
                    //layer.Add(adorner);
                    // pont_adorner = true;


                    //lineshapes.MouseEnter+=new System.Windows.Input.MouseEventHandler(lineshapes_MouseEnter);
                    //this.button1.Click += new System.EventHandler(this.button1_Click);
                    mainCanvas.Children.Add(lineshapes);
                }
            }
            //рисование стрелки 
            if (messageButton.IsChecked == true)
            {

                str_asinh = true;
            }

            if (linelifeButton.IsChecked == true)
            {
                Remove = false;

                lifeLine = new LifeLine();
                lifeLine.initWithPoint(e.GetPosition(mainCanvas));

                //добавляем в коллекцию
                mainCanvas.Children.Add(lifeLine);

                // undo redo commit
                //SaveDiagram(save_undo_rendo + count_save);
                //count_save++;
                //tekuhee_load++;

                cursorButton.IsChecked = true;
                this.cu_Checked(this, null);
            }
            //если выбрана клавиша текста
            if (commentButton.IsChecked == true)
            {
                Remove = false;

                commentBox = new CommentBox();
                commentBox.initWithPoint(e.GetPosition(mainCanvas));

                //добавляем в коллекцию
                mainCanvas.Children.Add(commentBox);

                cursorButton.IsChecked = true;
                this.cu_Checked(this, null);
            }
            //рисование возвратной стрелки
            if (selfMessageButton.IsChecked == true)
            {
                //событие с возвратом
                event_return = true;
                str_asinh = false;
                Remove = false;

                cursorButton.IsChecked = true;
                this.cu_Checked(this, null);
            }
            //курсор
            if (cursorButton.IsChecked == true)
            {
                Remove = false;
                str_asinh = false;
            }
            //удаление
            if (deleteButton.IsChecked == true)
            {
                str_asinh = false;
                Remove = true;
            }

            //
            state = MainState.Move;

            //UIElement line = result.VisualHit as UIElement;
            //if (line != null)
            //{ Mouse.Capture((UIElement)sender); }
            if (Remove == true)
            {
                Point pt = e.GetPosition((Canvas)sender);
                int s=0;
                HitTestResult result = VisualTreeHelper.HitTest((Canvas)sender, pt);
                DependencyObject figura = result.VisualHit;
                DependencyObject io;
                io = VisualTreeHelper.GetParent(result.VisualHit);

                Line l = figura as Line;
                if (l != null )
                {// индекс линии
                     s=((Canvas)sender).Children.IndexOf(l);
                     if (s > 1)
                     {
                         //получаем стрелку 
                         //если s линия тоs-1 должен быть обьект стрелка
                         Arrow bn = ((Canvas)sender).Children[s - 1] as Arrow;
                         if (bn != null)
                         {
                             // ((Canvas)sender).Children[bn.begin_el_n_FC];
                             if (bn.begin_el_n_FC < ((Canvas)sender).Children.Count && bn.end_el_n_FC < ((Canvas)sender).Children.Count)
                             {
                                 LifeLine rect_B = ((Canvas)sender).Children[bn.begin_el_n_FC] as LifeLine;
                                 LifeLine rect_E = ((Canvas)sender).Children[bn.end_el_n_FC] as LifeLine;
                                 if (rect_B != null && rect_E != null && rect_B.canvasfgh.Children.Count >= bn.begin_el_n_TC && rect_E.canvasfgh.Children.Count >= bn.end_ei_n_TC)
                                 {
                                     delte_strlka_n_I(((Canvas)sender), bn.begin_el_n_TC, bn.end_ei_n_TC, bn.begin_el_n_FC, bn.end_el_n_FC);

                                     //удаление линии
                                     ((Canvas)sender).Children.RemoveAt(s - 1);
                                     //удаление наконечника
                                     ((Canvas)sender).Children.RemoveAt(s - 1);
                                     //удалени обьекта стрелка
                                     ((Canvas)sender).Children.RemoveAt(s - 1);

                                     ((Canvas)sender).Children.RemoveAt(s - 1);

                                     //удаление начального рект
                                     rect_B.canvasfgh.Children.RemoveAt(bn.begin_el_n_TC);
                                     //удаление конечного рект
                                     rect_E.canvasfgh.Children.RemoveAt(bn.end_ei_n_TC);
                                     // delte_strlka_n_I(((Canvas)sender), bn.begin_el_n_TC, bn.end_ei_n_TC, bn.end_el_n_FC);
                                 }
                             }
                         }
                         else
                         { ((Canvas)sender).Children.Remove((UIElement)(((Canvas)sender).InputHitTest(pt))); }
                     }
                    
                }
                Polyline Poly_line = figura as Polyline;
                if (Poly_line != null)
                {// индекс линии
                    s = ((Canvas)sender).Children.IndexOf(Poly_line);
                    if (s > 1)
                    {
                        //получаем стрелку 
                        //если s линия тоs-1 должен быть обьект стрелка c стрелка с возвратом
                        SelfArrow bn = ((Canvas)sender).Children[s - 1] as SelfArrow;
                        if (bn != null)
                        {
                            if (bn.el_n_FC < ((Canvas)sender).Children.Count)
                            {
                                LifeLine rect = ((Canvas)sender).Children[bn.el_n_FC] as LifeLine;
                                if (rect != null && rect.canvasfgh.Children.Count >= bn.el_n_TC)
                                {
                                    delte_strlka_n_return(((Canvas)sender), bn.el_n_TC, bn.el_n_FC);

                                    ((Canvas)sender).Children.RemoveAt(s - 1);

                                    ((Canvas)sender).Children.RemoveAt(s - 1);

                                    rect.canvasfgh.Children.RemoveAt(bn.el_n_TC);
                                    //((Canvas)sender).Children.RemoveAt(s );

                                }
                            }
                        }
                    }
                }
                else
                {
                    ((Canvas)sender).Children.Remove((UIElement)(((Canvas)sender).InputHitTest(pt)));

                }
                    //UIElement df = (UIElement)((Canvas)sender).InputHitTest(pt);
                    // int a=((Canvas)sender).Children.IndexOf(df);
                    // UIElement d = (UIElement)df.InputHitTest(pt);
            }

            if (Remove == false)
            {
                Point pt = e.GetPosition((Canvas)sender);

                HitTestResult result = VisualTreeHelper.HitTest((Canvas)sender, pt);
                DependencyObject figura = result.VisualHit;
                DependencyObject io;
                if (result != null)
                {
                    io = VisualTreeHelper.GetParent(result.VisualHit);
                    System.Windows.Controls.TextBox texbox = io as System.Windows.Controls.TextBox;
                    if (texbox != null)
                    {
                        DependencyObject i_o = VisualTreeHelper.GetParent(io);
                        Canvas canva = i_o as Canvas;
                        if (canva != null)
                        {
                            fiure = true;
                            Mouse.Capture((UIElement)io);
                        }
                        else
                        {
                            life_time_capture = true;
                        }
                    }
                    else
                    {
                        //Rectangle as_st = figura as Rectangle;
                        //if (as_st != null)
                        //{
                        //    fiure = true;
                        //    Mouse.Capture((UIElement)figura);

                        //}
                        Ellipse ellipdf = figura as Ellipse;
                        if (ellipdf != null)
                        {
                            fiure = true;
                            Mouse.Capture((UIElement)figura);

                        }
                        Canvas canva = io as Canvas;
                        if (canva != null)
                        {
                            Line lon = figura as Line;
                            if (lon != null)
                            {
                                //если линия захватываем мышь для перетаскивания
                                linr_ = true;
                                //находим расстояние от клика до начала и конца линнии 
                                x1 = Math.Abs(pt.X - lon.X1) * Math.Abs(pt.X - lon.X1) + Math.Abs(pt.Y - lon.Y1) * Math.Abs(pt.Y - lon.Y1);
                                x2 = Math.Abs(pt.X - lon.X2) * Math.Abs(pt.X - lon.X2) + Math.Abs(pt.Y - lon.Y2) * Math.Abs(pt.Y - lon.Y2);
                                //выбираем какого конца будем изменять координаты после перетаскивания
                                if (x1 < x2)
                                {
                                    point_x1 = true;
                                }
                                //((life_time)sender).dro = true;
                                Mouse.Capture((UIElement)figura);
                            }
                        }
                    }
                }
            }
            else
            {
                //----------------------------удаление элементов-----------------------------------
                //
                //точка клика
                Point pt = e.GetPosition((Canvas)sender);
                //
                HitTestResult result = VisualTreeHelper.HitTest((Canvas)sender, pt);
                DependencyObject figura = result.VisualHit;
                DependencyObject io;
                if (result != null)
                {
                    //получаем родительский элемент
                    io = VisualTreeHelper.GetParent(result.VisualHit);
                    System.Windows.Controls.TextBox texbox = io as System.Windows.Controls.TextBox;
                    if (texbox != null)
                    {
                        //получаем родительский элемент
                        DependencyObject i_o = VisualTreeHelper.GetParent(io);
                        Canvas canva = i_o as Canvas;
                        if (canva != null)
                        {
                            ((Canvas)sender).Children.Remove((UIElement)io);
                        }
                    }
                }
            }
        }


        private void delte_strlka_n_return(Canvas fd, int n_des_E, int count_Lif__FC)
        {
            int Casd = fd.Children.Count;
          //перебираем все стрелки
            for (int j = 0; j < Casd; j++)
            {
                Arrow bn = fd.Children[j] as Arrow;
                if (bn != null)
                {
                    //совпадает начало удаляемой lif_time и начало хранимое в стрелке
                    if (count_Lif__FC == bn.begin_el_n_FC)
                    {
                        if (bn.begin_el_n_TC > n_des_E)
                        {
                            bn.begin_el_n_TC--;
                        }
                    }
                    //совпадает начало удаляемой lif_time и конец хранимое в стрелке
                    if (count_Lif__FC == bn.end_el_n_FC)
                    {
                        if (bn.end_ei_n_TC > n_des_E)
                        {
                            bn.end_ei_n_TC--;
                        }

                    }

                } 
                //стрелка с возвратом
                SelfArrow str_vozvrat= fd.Children[j] as SelfArrow;
                if (str_vozvrat != null)
                {
                    //совпалают линния хизни
                    if (count_Lif__FC == str_vozvrat.el_n_FC)
                    {
                       // индекс удаляемой срелки с возвратом меньше чем найденной
                        if (str_vozvrat.el_n_TC > n_des_E)
                        {
                            str_vozvrat.el_n_TC--;
                        }
                    }

                }
            }     
        }

        /// <summary>
        ///  уменьшение индексов в обьекте стрелка 
        /// </summary>
        /// <param name="fd"> канвас где расположены стрелки </param>
        /// <param name="n_des">ИНДЕКС УДАЛЕННОГО ЭЛЕМЕНТА (рект) начала стрелки</param>
        /// <param name="count_Lif">ИНДЕКС  ЭЛЕМЕНТА (линии жизни из которой удалем рект)</param>
        /// 
        private void delte_strlka_n_I(Canvas fd, int n_des_B, int n_des_E, int count_Lif_begin_FC, int count_Lif_end_FC)
        {
            int Casd = fd.Children.Count;
              //перебираем все стрелки
            for (int j = 0; j < Casd; j++)
            {
                 Arrow bn = fd.Children[j] as Arrow;
                 if (bn != null)
                 {
                     //совпадает конец  начало lif_time удаляемого рект со хранимой в стрелке
                     if (count_Lif_begin_FC == bn.begin_el_n_FC && count_Lif_end_FC == bn.end_el_n_FC)
                     {
                         if (bn.begin_el_n_TC > n_des_B && bn.end_ei_n_TC > n_des_E)
                         {
                             bn.begin_el_n_TC--;
                             bn.end_ei_n_TC--;
                         }

                     }
                     else {
                         //совпадает начало удаляемой lif_time и начало хранимое в стрелке
                         if (count_Lif_begin_FC == bn.begin_el_n_FC )
                         {
                             if (bn.begin_el_n_TC > n_des_B)
                             {
                                 bn.begin_el_n_TC--;
                             }
                         }
                         //совпадает конец удаляемой lif_time и начало хранимое в стрелке
                         if (count_Lif_end_FC == bn.begin_el_n_FC)
                         {
                             if (bn.begin_el_n_TC > n_des_E)
                             {
                                 bn.begin_el_n_TC--;
                             }

                         }
                         //совпадает конец удаляемой lif_time и конец хранимое в стрелке
                         if (count_Lif_end_FC == bn.end_el_n_FC)
                         {
                             if (bn.end_ei_n_TC > n_des_E)
                             {
                                 bn.end_ei_n_TC--;
                             }

                         }
                         //совпадает начало удаляемой lif_time и конец хранимое в стрелке
                         if (count_Lif_begin_FC == bn.end_el_n_FC)
                         {
                             if (bn.end_ei_n_TC > n_des_B)
                             {
                                 bn.end_ei_n_TC--;
                             }
                         }
                     }

                     ////индекс линии жизни должен совпадать 
                     ////или с  началом стрелки
                     //if (count_Lif == bn.begin_el_n_FC)
                     //{
                     //    //проверяем индекс рект он должен быть больше удаленного рект
                     //    if (bn.begin_el_n_TC > n_des_B)
                     //            //уменьшаем индекс положения рект
                     //            bn.begin_el_n_TC -= 1;
                     //        if (bn.end_ei_n_TC > n_des_E)
                     //            bn.end_ei_n_TC -= 1;
                     
                     //}
                     ////c концом стрелки
                     // if (count_Lif == bn.end_el_n_FC)
                     //{
                     //    //проверяем индекс рект он должен быть больше удаленного рект
                     //    if (bn.begin_el_n_TC > n_des_B)
                     //            //уменьшаем индекс положения рект
                     //            bn.begin_el_n_TC -= 1;
                     //        if (bn.end_ei_n_TC > n_des_E)
                     //            bn.end_ei_n_TC -= 1;
                     
                     //}
  
                 }
                 //стрелка с возвратом
                 SelfArrow str_vozvrat = fd.Children[j] as SelfArrow;
                 if (str_vozvrat != null)
                 {
                     //совпалают линния хизни
                     if (count_Lif_end_FC == str_vozvrat.el_n_FC)
                     {
                         // индекс удаляемой срелки с возвратом меньше чем найденной
                         if (str_vozvrat.el_n_TC > n_des_E)
                         {
                             str_vozvrat.el_n_TC--;
                         }
                     }
                     //совпалают линния хизни
                     if (count_Lif_begin_FC == str_vozvrat.el_n_FC)
                     {
                         // индекс удаляемой срелки с возвратом меньше чем найденной
                         if (str_vozvrat.el_n_TC > n_des_B)
                         {
                             str_vozvrat.el_n_TC--;
                         }
                     }

                 }

            }
        }
        
        
        private void dec_life_time(int index_life_time_del)
        {
               int Casd = mainCanvas.Children.Count;
                    //перебираем все стрелки
               for (int j = Casd - 1; j > 0; j--)
               {
                   LifeLine bn = mainCanvas.Children[j] as LifeLine;
                   if (bn != null)
                   {
                       if (bn.id > index_life_time_del)
                       {
                           bn.id--;

                       }
                   }
                  SelfArrow del_v_str = mainCanvas.Children[j] as SelfArrow;
                  if (del_v_str != null)
                  {
                      if (del_v_str.el_n_FC > index_life_time_del)
                      {
                          del_v_str.el_n_FC--;
                      }
                  }
                  Arrow del_str = mainCanvas.Children[j] as Arrow;
                  if (del_str != null)
                  {
                      if (del_str.begin_el_n_FC > index_life_time_del)
                      {
                          del_str.begin_el_n_FC--;
                      }
                      if (del_str.end_ei_n_TC > index_life_time_del)
                      {
                          del_str.end_ei_n_TC--;
                      }
                  }

               }
        }
        
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//----------------------------------------------перетаскивание элементов-------------------------------------------------------//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 
            private void ellip_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)

        {
            Ellipse df = (Ellipse)sender;
            df.Fill = Brushes.Red;

        }

        private void ellip_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            Ellipse df = (Ellipse)sender;
            df.Fill = Brushes.Beige;

        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            redacto =true;

        }
        private void cmdSelectMove_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //scal = false;
        }
        private void cmdSelectMove_Click(object sender, RoutedEventArgs e)
        {

            numb = 1;
        }
        //private void canvas1_MouseMove(object sender, MouseEventArgs e)
        //{
        //    Ellipse asd=new Ellipse();
        //    if (asd == sender)
        //        asd = (Ellipse)sender;


        //    asd.Width = Math.Abs(xn - e.GetPosition(canvas1).X);

       // }
        private void new_prog_Click(object sender, RoutedEventArgs e)
        {

            DialogResult dr;
           // if (figures.Count > 0)
           // {
                dr = System.Windows.Forms.MessageBox.Show( "Do you wish to save the current Diagram?",
                  "Before Creating a new Diagram...", MessageBoxButtons.YesNoCancel);
                if (dr == System.Windows.Forms.DialogResult.Cancel) return;
                if (dr == System.Windows.Forms.DialogResult.Yes) 
                {
                    SaveFileDialog SaveFileDialog1 = new SaveFileDialog();

                    SaveFileDialog1.Filter = "files (*.avg)|*.avg";
                    SaveFileDialog1.RestoreDirectory = true;

                    if (SaveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        try
                        {
                            SaveDiagram(SaveFileDialog1.FileName);
                        }
                        catch (Exception ex)
                        {
                            System.Windows.Forms.MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                        }
                    } 
                };
            //}
            //ClearDiagram();

                mainCanvas.Children.Clear();

        }

       
        void OnMouseEnterHandler(object sender, System.Windows.Input.MouseEventArgs e)
        {
            el = new Ellipse();
            el = (Ellipse)sender;
            el.Fill = Brushes.Bisque;
        }

        public double xn { get; set; }

        public IWin32Window thi { get; set; }

        public Ellipse el { get; set; }

        private void grid1_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {  
        }
        private void canvas1_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
        }

        private void delete_Click(object sender, RoutedEventArgs e)
        {
            Remove = true;
            event_return = false;
            str_asinh = false;

            state = MainState.Remove;
        }
        private void li_str_Click(object sender, RoutedEventArgs e)
        {
            Remove = false;
            str_asinh = true;
            numb = 1;
            event_return = false;
        }
        private void cu_Checked(object sender, RoutedEventArgs e)
        {
            str_asinh = false;
            event_return = false;
            Remove = false;

            state = MainState.Move;
        }
        //возвратная стрелка
        private void line_vozvrat_Click(object sender, RoutedEventArgs e)
        {
            event_return = true;
            str_asinh = false;
            Remove = false;

            state = MainState.SelfMessage;
        }
        
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//---------------------------сохранение и загрузка---------------------------------------------------------------//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            StreamWriter sr;
            SaveFileDialog SaveFileDialog1 = new SaveFileDialog();

            SaveFileDialog1.Filter = "files (*.avg)|*.avg|files (*.)|*.*";
       
            SaveFileDialog1.RestoreDirectory = true;

            if (SaveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    SaveDiagram(SaveFileDialog1.FileName);
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            } 
           
        }
        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            //openFileDialog1.Filter = "txt files (*.txt)|*.txt";
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.Filter = "files (*.avg)|*.avg|files (*.)|*.*";
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    LoadFile(openFileDialog1.FileName);
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
           
        }

        private void LoadFile(string name_F)
        {
            //System.IO.MemoryStream stream = new System.IO.MemoryStream();


            mainCanvas.Children.Clear();
            //FileStream fs = File.OpenRead("qwerty.xml");



            Line Lining;
            Arrow li_;
            LifeLine new_;
            Save Sav_ = new Save();
            Sav_.load_all(name_F);

            int count = Sav_.List_L_T.Count;
            for (int i = 0; i < count; i++)
            {
                new_ = new LifeLine();
                new_.initWithPoint(new Point(Sav_.List_L_T[i].set_left, Sav_.List_L_T[i].Set_top));

                int count_rect = Sav_.List_L_T[i].rect_List.Count;
                for (int j = 0; j < count_rect; j++ )
                {

                    if (Sav_.List_L_T[i].rect_List[j].Hight != 50)
                    {
                        new_.new_Rect(0);
                    }
                    else {
                        new_.new_Rect(Sav_.List_L_T[i].rect_List[j].Hight);
                    }
                
                    new_.add_rect_canvac(Sav_.List_L_T[i].rect_List[j].Set_top,Sav_.List_L_T[i].rect_List[j].Set_top);
                   // Rect.Height= Sav_.List_L_T[i].rect_List[j].Hight;
                    //Canvas.SetTop(Rect, );
                    //Canvas.SetLeft(Rect, Sav_.List_L_T[i].rect_List[j].Set_left);
                   // new_.canvasfgh.Children.Add(Rect);
                }

            
                new_.textBox.Text = Sav_.List_L_T[i].text;
                new_.line.Y2 = Sav_.List_L_T[i].Line_Y;

                new_.id = mainCanvas.Children.Count;
                mainCanvas.Children.Add(new_);
                
            }
            //отображаем все стрелки
            int count_strel = Sav_.List_strelca.Count;
            for (int z = 0; z < count_strel; z++)
            {
                li_ = new Arrow();
                //инилизация 
                li_.line_prop_();
                //заполняем свойства зависимости
                li_.begin_el_n_FC = Sav_.List_strelca[z].begin_el_n_FC;
                li_.begin_el_n_TC = Sav_.List_strelca[z].begin_el_n_TC;
                li_.end_ei_n_TC = Sav_.List_strelca[z].end_ei_n_TC;
                li_.end_el_n_FC = Sav_.List_strelca[z].end_el_n_FC;
                //положение
                li_.line.X1 = Sav_.List_strelca[z].X1;
                li_.line.X2 = Sav_.List_strelca[z].X2;
                li_.line.Y1= Sav_.List_strelca[z].Y12;
                li_.line.Y2=Sav_.List_strelca[z].Y12;

                //добавление на канвас
                mainCanvas.Children.Add(li_);
                //добавляем линию и наконечник
                li_.add_canvas(mainCanvas);
            }
            int count_coment = Sav_.List_textbox.Count;
            for (int k = 0; k < count_coment; k++)
            {
                
                commentBox = new CommentBox();
                Thickness bp = new Thickness(5);
                commentBox.BorderThickness = bp;
                commentBox.BorderBrush = Brushes.Chocolate;
                commentBox.Text = Sav_.List_textbox[k].Texts;
                Canvas.SetLeft(commentBox, Sav_.List_textbox[k].Set_left);
                Canvas.SetTop(commentBox, Sav_.List_textbox[k].Set_top);
                mainCanvas.Children.Add(commentBox);
            }
            int count_lineshape = Sav_.List_liner.Count;
            for (int fu=0; fu < count_lineshape; fu++)
            {
                Lining = new Line();
                Lining.StrokeEndLineCap = PenLineCap.Triangle;  //задает наконечник
                Lining.Stroke = Brushes.Black;                   //способ закраски контура fill не исполь solicolorbrash

                Lining.StrokeMiterLimit = 10;
                DoubleCollection D_C_l = new DoubleCollection(2);
                D_C_l.Add(4);
                D_C_l.Add(2);
                Lining.StrokeDashArray = D_C_l;                  //задает пунктир
                Lining.StrokeThickness = 2;    
                Lining.X1 = Sav_.List_liner[fu].X1;
                Lining.X2 = Sav_.List_liner[fu].X2;
                Lining.Y1 = Sav_.List_liner[fu].Y1;
                Lining.Y2 = Sav_.List_liner[fu].Y2;
                mainCanvas.Children.Add(Lining);
                
            }

        }
        private void SaveDiagram(string name_F)
        {

            Save Sav_ = new Save();
            Line serch_line;
            LifeLine L_T_searce ;
            Arrow L_Strelka_Searh;
            life_t L_T;
            System.Windows.Controls.TextBox text_serce;
            int count;
            count = mainCanvas.Children.Count;
           //перебираем все элементы
            for (int i=0; i < count; i++ )
            {
                L_T_searce = new LifeLine();
                L_T_searce = mainCanvas.Children[i] as LifeLine;
                if (L_T_searce != null)
                {
                    L_T = new editor.life_t();
                    int coun_rect = L_T_searce.canvasfgh.Children.Count;
                    for (int j = 0; j < coun_rect; j++)
                    {
                        Rectangle R_T = L_T_searce.canvasfgh.Children[j] as Rectangle;
                        if (R_T != null)
                        {
                            // сохранение всех события
                            Rectan Rec_ = new Rectan();
                            Rec_.Set_top = Canvas.GetTop(R_T) + 21;
                            Rec_.Set_left = Canvas.GetLeft(R_T);
                            Rec_.Hight = R_T.Height;
                            // добавление события в rect_List хронящийся в линиии жизни
                            L_T.rect_List.Add(Rec_);   //
                        }
                    }
                    // сохранение характеристик life_time

                    L_T.set_left = Canvas.GetLeft(L_T_searce);
                    L_T.Set_top = Canvas.GetTop(L_T_searce);
                    L_T.save_life_t(L_T_searce.textBox.Text, L_T_searce.line.Y2);
                    // добавление в List_L_T хронящися в классе Save
                    Sav_.List_L_T.Add(L_T);
                }
                //находим стрелку
                L_Strelka_Searh = new Arrow();
                L_Strelka_Searh = mainCanvas.Children[i] as Arrow;
                if (L_Strelka_Searh != null)
                {
                    //сохранение стрелки в обьект класса save
                    strelca srtelca = new strelca();
                    //свойства зависимости 
                    srtelca.begin_el_n_FC = L_Strelka_Searh.begin_el_n_FC;
                    srtelca.begin_el_n_TC = L_Strelka_Searh.begin_el_n_TC;
                    srtelca.end_ei_n_TC=L_Strelka_Searh.end_ei_n_TC;
                    srtelca.end_el_n_FC = L_Strelka_Searh.end_el_n_FC;
                    //положение
                    srtelca.X1 = L_Strelka_Searh.line.X1;
                    srtelca.X2 = L_Strelka_Searh.line.X2;
                    srtelca.Y12 = L_Strelka_Searh.line.Y1;
                    //добавление
                    Sav_.List_strelca.Add(srtelca);
                    break;
                }
                text_serce = new System.Windows.Controls.TextBox();
                text_serce = mainCanvas.Children[i] as System.Windows.Controls.TextBox;
                if (text_serce != null)
                {
                    // сохранение коментария в объект класса save
                    Textboxs text_boxes = new Textboxs();
                    text_boxes.Set_top = Canvas.GetTop(text_serce);
                    text_boxes.Set_left = Canvas.GetLeft(text_serce);
                    text_boxes.Texts = text_serce.Text;
                    // добавление
                    Sav_.List_textbox.Add(text_boxes);
                }
                serch_line = new Line();
                serch_line = mainCanvas.Children[i] as Line;
                if (serch_line != null)
                {
                    // сохранение штрихованной лини в объект класса save
                    Liner liner_shape = new Liner();
                    liner_shape.X1 = serch_line.X1;
                    liner_shape.X2 = serch_line.X2;
                    liner_shape.Y1 = serch_line.Y1;
                    liner_shape.Y2 = serch_line.Y2;
                    // добавление
                    Sav_.List_liner.Add(liner_shape);
                }
            }
            Sav_.save_all(name_F);  
        }
        //сохранение в картинку
        public static void SaveCanvasToFile(Canvas surface, string filename)
        {
            Size size = new Size(surface.Width, surface.Height);

            surface.Measure(size);
            surface.Arrange(new Rect(size));

            // Create a render bitmap and push the surface to it
            RenderTargetBitmap renderBitmap =
              new RenderTargetBitmap(
                (int)size.Width,
                (int)size.Height,
                96d,
                96d,
                PixelFormats.Pbgra32);
            renderBitmap.Render(surface);

            // Create a file stream for saving image
            using (FileStream outStream = new FileStream(filename, FileMode.Create))
            {
                BmpBitmapEncoder encoder = new BmpBitmapEncoder();
                // push the rendered bitmap to it
                encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
                // save the data to the stream
                encoder.Save(outStream);
            }
        }

        private void MenuItem_Click_2(object sender, RoutedEventArgs e)
        {
         
            SaveFileDialog SaveFileDialog1 = new SaveFileDialog();

            //SaveFileDialog1.Filter = "txt files (*.txt)|*.txt";
            SaveFileDialog1.RestoreDirectory = true;
           

            if (SaveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    SaveCanvasToFile(mainCanvas, SaveFileDialog1.FileName);
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            } 
           //SaveWindow(this, 96, "window.png");
           //SaveCanvas_2(this, canvas1, 96, "window.png");
        }
        public static void SaveWindow(Window window, int dpi, string filename)
        {

            var rtb = new RenderTargetBitmap(
                (int)window.Width, //width
                (int)window.Width, //height
                dpi, //dpi x
                dpi, //dpi y
                PixelFormats.Pbgra32 // pixelformat
                );
            rtb.Render(window);

            SaveRTBAsPNG(rtb, filename);

        }
        private static void SaveRTBAsPNG(RenderTargetBitmap bmp, string filename)
        {
            var enc = new System.Windows.Media.Imaging.PngBitmapEncoder();
            enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp));

            using (var stm = System.IO.File.Create(filename))
            {
                enc.Save(stm);
            }
        }
        public static void SaveCanvas_2(Window window, Canvas canvas, int dpi, string filename)
        {
            Size size = new Size(window.Width, window.Height);
            canvas.Measure(size);
            //canvas.Arrange(new Rect(size));

            var rtb = new RenderTargetBitmap(
                (int)window.Width, //width
                (int)window.Height, //height
                dpi, //dpi x
                dpi, //dpi y
                PixelFormats.Pbgra32 // pixelformat
                );
            rtb.Render(canvas);

            SaveRTBAsPNG(rtb, filename);
        }
       //перейти на шаг вперед
        private void button2_Click(object sender, RoutedEventArgs e)
        {

            if (tekuhee_load <count_save && tekuhee_load >= 0)
            {
                mainCanvas.Children.Clear();
                //переходим к файлу на шаг позже
               // tekuhee_load = count_save;
                tekuhee_load++;
                LoadFile(save_undo_rendo + tekuhee_load);

            }
           

        }
        //перейти на шаг назад
        private void button1_Click_1(object sender, RoutedEventArgs e)
        {
            if(tekuhee_load<=count_save&&tekuhee_load>0)
            {
                mainCanvas.Children.Clear();
                //переходим к файлу на шаг раньше
               
                tekuhee_load--;
                LoadFile(save_undo_rendo + tekuhee_load);
            }
        }

        private void Window_MouseWheel(object sender, MouseWheelEventArgs e)
        {
                   
                if (System.Windows.Input.Keyboard.IsKeyDown(Key.Z))
                {
                   

                    if (e.Delta == 120)
                    {
                           if(zoom<1.5)
                           {
                        mainCanvas.RenderTransform = new ScaleTransform(zoom, zoom);
                               zoom+=0.1;
                           }

                    }
                    if (e.Delta == -120)
                    {
                        if (zoom > 0.5)
                        {
                            mainCanvas.RenderTransform = new ScaleTransform(zoom, zoom);
                            zoom -= 0.1;
                        }
                    }
                    
                     textBlock1.Text=zoom.ToString();
                

                    
                }

            

        }
    
      

       

   
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//-------------------------------------- lifeLine ---------------------------------------------------------------//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////


        public void life_t_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            // a.Focus();
            //s = a.;
        }

        public void life_t_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            //if (controlmove)
            //{
            //    A1 = sender as life_time;

            //    //System.Drawing.Size s0 = new System.Drawing.Size((int)(e.GetPosition(canvas1).X - p.X), (int)(e.GetPosition(canvas1).Y - p.Y));
            //    if (e.LeftButton == MouseButtonState.Pressed)
            //    {

            //        Canvas.SetTop(A1, (e.GetPosition(canvas1).Y - p.X));
            //        Canvas.SetLeft(A1, (e.GetPosition(canvas1).X - p.Y));
            //    }
            //}  
        }

        public void lineClicked(LifeLine lifeLine, System.Windows.Point relativePosition)
        {

            if (life_time_capture == true)
            {
                X_0 = Canvas.GetLeft(lifeLine);
                Mouse.Capture(lifeLine);
            }

            HitTestResult result = VisualTreeHelper.HitTest(mainCanvas, relativePosition);
            DependencyObject io;
            if (result != null)
            {
                io = VisualTreeHelper.GetParent(result.VisualHit);
                DependencyObject i;
                i = VisualTreeHelper.GetParent(io);
                if (result != null)
                {
                    Line lon = result.VisualHit as Line;
                    if (lon != null)
                    {
                        //рисуем два события и стрелку
                        if (str_asinh == true)
                        {

                            ////////////////////////////////////////////рисуем стрелку с линией времени////////////////////////////////////////////////

                            lifeLine.dro = false;
                            if (numb == 1)
                            {
                                lifeLine.new_Rect(0);

                                //-----------------позиция начала стрелки 
                                arrow = new Arrow();
                                //запоминаем Y2 для линии
                                line_Y2 = relativePosition.Y;
                                //начало линии
                                arrow.pos_line_B(new Point(relativePosition.X + 10, line_Y2));
                                //проперти линии
                                arrow.line_prop_();
                                //запоминаем номер в коллекции рект 1 начало стрелки 
                                arrow.begin_el_n_FC = lifeLine.id;

                                //запоминаем номер в коллекции рект 1 начало стрелки 
                                arrow.begin_el_n_TC = (((Canvas)i).Children.Count);
                                // добавляем в коллекцию рект 1 начало стрелки 
                                //((Canvas)i).Children.Add(rest1);
                                lifeLine.add_rect_canvac(Canvas.GetLeft(lifeLine), relativePosition.Y);
                                //добавляем координаты второго рект
                                rect_2_Y = relativePosition.Y;
                                numb--;
                            }
                            else
                            {
                                //-----------------позиция конца стрелки
                                //list_strelka.Add(li_);
                                arrow.pos_line_E_X2(relativePosition.X - 10);
                                arrow.pos_line_E_Y2(line_Y2);

                                //запоминаем номер линии жизни на
                                arrow.end_el_n_FC = lifeLine.id;

                                ////-----------------рисуем второй рект

                                lifeLine.new_Rect(0);

                                //добавлем обект стрелка

                                mainCanvas.Children.Add(arrow);
                                //добавляем линию и наконечник
                                arrow.add_canvas(mainCanvas);

                                //запоминаем номер в коллекции рект 2 конец стрелки 
                                arrow.end_ei_n_TC = (((Canvas)i).Children.Count);

                                // добавляем в коллекцию рект 2 конец стрелк
                                //((Canvas)i).Children.Add(rest2);
                                lifeLine.add_rect_canvac(relativePosition.X - 10, rect_2_Y);

                                //разрешаем перетаскивание линию -линии жизни 2
                                //((life_time)sender).dro = true;
                                numb = 1;

                            }
                        }
                        /////////////////////////////////////////////////рисуем стрелку с линией времени////////////////////////////////////////////////




                        //////////////////////////////////////////////рисуем событие с возвратом//////////////////////////////////////////////
                        if (event_return == true)
                        {
                            //разрешаем  увелечение  линии жизни
                            lifeLine.dro = false;

                            lifeLine.new_Rect(0);
                            //возваратная стрелка
                            SelfArrow str_ret = new SelfArrow();
                            str_ret.numb_l_t_in_canvas = lifeLine.id;

                            str_ret.line_prop_str_return(relativePosition.X + 10, relativePosition.Y);

                            str_ret.el_n_TC = (((Canvas)i).Children.Count);

                            lifeLine.add_rect_canvac(Canvas.GetLeft(lifeLine), relativePosition.Y);

                            str_ret.el_n_FC = lifeLine.id;



                            //добавление обекта  стрелки с возвратом на главный канвас
                            mainCanvas.Children.Add(str_ret);
                            //добавление   стрелки с возвратом на главный канвас
                            str_ret.add_canvas(mainCanvas);
                        }
                        //////////////////////////////////////////////рисуем событие с возвратом//////////////////////////////////////////////

                        if (event_return == false && str_asinh == false)
                        { lifeLine.dro = true; }
                    }
                }
            }

            if (Remove == true)
            {
                LifeLine delete_l_time = lifeLine;

                if (delete_l_time != null)
                {
                    int f = 0;
                    int Casd = mainCanvas.Children.Count;
                    //перебираем все стрелки
                    for (int j = Casd - 1; j > 0; j--)
                    {
                        Arrow bn = mainCanvas.Children[j] as Arrow;
                        if (bn != null)
                        {

                            LifeLine rect_B = mainCanvas.Children[bn.begin_el_n_FC] as LifeLine;
                            LifeLine rect_E = mainCanvas.Children[bn.end_el_n_FC] as LifeLine;

                            //совпадает начало удаляемой lif_time и начало хранимое в стрелке
                            if (delete_l_time.id == bn.begin_el_n_FC || delete_l_time.id == bn.end_el_n_FC)
                            {
                                delte_strlka_n_I(mainCanvas, bn.begin_el_n_TC, bn.end_ei_n_TC, bn.begin_el_n_FC, bn.end_el_n_FC);

                                //удаление линии
                                mainCanvas.Children.RemoveAt(j);
                                //удаление наконечника
                                mainCanvas.Children.RemoveAt(j);
                                //удалени обьекта стрелка
                                mainCanvas.Children.RemoveAt(j);

                                mainCanvas.Children.RemoveAt(j);
                                //  Casd -= 4;

                                //удаление начального рект
                                rect_B.canvasfgh.Children.RemoveAt(bn.begin_el_n_TC);
                                //удаление конечного рект
                                rect_E.canvasfgh.Children.RemoveAt(bn.end_ei_n_TC);




                                j--;
                            }
                        }
                        //получаем стрелку 
                        //если s линия тоs-1 должен быть обьект стрелка c стрелка с возвратом
                        SelfArrow del_v_str = mainCanvas.Children[j] as SelfArrow;
                        if (del_v_str != null)
                        {
                            if (del_v_str.el_n_FC < (mainCanvas.Children.Count))
                            {
                                LifeLine rect = mainCanvas.Children[del_v_str.el_n_FC] as LifeLine;
                                if (delete_l_time.id == del_v_str.el_n_FC)
                                {
                                    delte_strlka_n_return(mainCanvas, del_v_str.el_n_TC, del_v_str.el_n_FC);

                                    mainCanvas.Children.RemoveAt(j);
                                    mainCanvas.Children.RemoveAt(j);

                                    // Casd -= 2;
                                    //((Canvas)sender).Children.RemoveAt(s );
                                    rect.canvasfgh.Children.RemoveAt(del_v_str.el_n_TC);



                                }
                            }
                        }
                    }
                    dec_life_time(delete_l_time.id);

                    mainCanvas.Children.Remove(delete_l_time);
                    //уменьшение индекса n_child

                }
                else
                {
                    mainCanvas.Children.Remove(lifeLine);
                }

            }
        }

        public void life_t_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (life_time_capture == true)
            {
                life_time_capture = false;
                LifeLine line = sender as LifeLine;
                if (line != null)
                {
                    Canvas.SetTop(((LifeLine)sender), 20);
                    Canvas.SetLeft(((LifeLine)sender), e.GetPosition(mainCanvas).X);

                    Mouse.Capture(null);
                    // VisualCollection df = new VisualCollection();
                    int Casd = mainCanvas.Children.Count;
                    for (int j = 0; j < Casd; j++)
                    {
                        Arrow l1 = mainCanvas.Children[j] as Arrow;
                        if (l1 != null)
                        {
                            //находим принадлежащие  линии Жизни
                            if (l1.begin_el_n_FC == ((LifeLine)sender).id)
                            {
                                //передвигаем начало стрелки
                                double delta = l1.line.X1 - X_0;
                                l1.pos_line_B_X1(delta + e.GetPosition(mainCanvas).X);
                            }
                            if (l1.end_el_n_FC == ((LifeLine)sender).id)
                            {
                                //передвигаем  конец
                                double delta = l1.line.X2 - X_0;
                                l1.pos_line_E_X2(delta + e.GetPosition(mainCanvas).X);
                            }
                        }
                        SelfArrow l_return = mainCanvas.Children[j] as SelfArrow;

                        //перерисовываем стрелку с возвратом
                        if (l_return != null)
                        {
                            if (l_return.numb_l_t_in_canvas == ((LifeLine)sender).id)
                            {
                                PointCollection asd = l_return.str_return.Points;
                                Point Begin_point = asd[0];
                                double delta = Begin_point.X - X_0;
                                l_return.line_prop_str_return(delta + e.GetPosition(mainCanvas).X, Begin_point.Y);
                            }
                        }
                        //опред области попадания
                        Line l = mainCanvas.Children[j] as Line;
                        if (l != null)
                        {

                            //int h = list_strelka.Count;

                            //for (int i = 0; i < h; i++)

                            //{
                            //    if (j == list_strelka[i].N)
                            //    {
                            //        if(list_strelka[i].begin_el_n_FC==)
                            //        {

                            //        }

                            //    }
                            //}

                            //    if (((Line)canvas1.Children[j]).X2 > X_0 && ((Line)canvas1.Children[j]).X2 < X_0 + 60)
                            //    {
                            //        double delta = ((Line)canvas1.Children[j]).X2 - X_0;
                            //        ((Line)canvas1.Children[j]).X2 = delta + e.GetPosition(canvas1).X;
                            //    }
                            //if (((Line)canvas1.Children[j]).X1 > X_0 + 60 && ((Line)canvas1.Children[j]).X1 < X_0 + 120)
                            //{
                            //    double delta = ((Line)canvas1.Children[j]).X1 - X_0;
                            //    ((Line)canvas1.Children[j]).X1 = delta + e.GetPosition(canvas1).X;
                            //}

                        }

                    }
                }

                //if (controlmove)
                //{
                //    System.Windows.Input.Mouse.Capture(null);
                //}
            }
        }
     
    }
}
